using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityEngine.EventSystems;

/// <summary>
/// 路径高亮状态枚举
/// </summary>
public enum PathHighlightState
{
    Normal,     // 正常状态
    Hover,      // 鼠标悬停
    Valid,      // 可放置（拖拽物品时）
    Invalid     // 不可放置（拖拽物品时）
}

/// <summary>
/// 路径高亮管理器 - 支持可用/不可用/悬停不同tile
/// </summary>
public class PathHighlightManager : MonoBehaviour
{
    [Header("高亮设置")]
    public TileBase normalTile;        // 正常路径瓦片
    public TileBase hoverTile;         // 悬停高亮瓦片
    public TileBase validTile;         // 可放置高亮瓦片
    public TileBase invalidTile;       // 不可放置高亮瓦片

    [Header("高亮层设置")]
    public Tilemap highlightTilemap;   // 高亮层瓦片地图

    // 私有变量
    private List<Vector3Int> currentPath = new List<Vector3Int>();
    private Vector3Int lastHoveredCell = Vector3Int.zero;
    private PathHighlightState currentState = PathHighlightState.Normal;
    private bool isDragging = false;
    private bool canPlaceItem = false;

    private Camera mainCamera;
    private Dictionary<Vector3Int, TileBase> originalTiles = new Dictionary<Vector3Int, TileBase>();

    private void Awake()
    {
        mainCamera = Camera.main;
    }

    private void OnEnable()
    {
        EventHandler.StartFollowingPath += OnStartFollowingPath;
        EventHandler.FinishFollowingPath += OnFinishFollowingPath;
        EventHandler.AfterSceneLoadEvent += OnAfterSceneLoadEvent;
    }

    private void OnDisable()
    {
        EventHandler.StartFollowingPath -= OnStartFollowingPath;
        EventHandler.FinishFollowingPath -= OnFinishFollowingPath;
        EventHandler.AfterSceneLoadEvent -= OnAfterSceneLoadEvent;
    }

    private void OnAfterSceneLoadEvent()
    {
        highlightTilemap = GameObject.FindWithTag("HightTile").GetComponent<Tilemap>();
    }

    private void Update()
    {
        if (currentPath.Count == 0 || highlightTilemap == null) return;
        HandleMouseInteraction();
    }

    private void HandleMouseInteraction()
    {
        Vector3Int cell = GetMouseCellPosition();
        if (cell != lastHoveredCell)
        {
            // 清除上次高亮
            highlightTilemap.SetTile(lastHoveredCell, null);

            // 只高亮路径上的格子
            if (currentPath.Contains(cell))
            {
                highlightTilemap.SetTile(cell, GetCurrentHighlightTile());
            }
            lastHoveredCell = cell;
        }
    }

    private Vector3Int GetMouseCellPosition()
    {
        Vector3 mouseWorldPos = mainCamera.ScreenToWorldPoint(Input.mousePosition);
        mouseWorldPos.z = 0;
        return highlightTilemap.layoutGrid.WorldToCell(mouseWorldPos);
    }

    private TileBase GetCurrentHighlightTile()
    {
        switch (currentState)
        {
            case PathHighlightState.Hover:
                return hoverTile;
            case PathHighlightState.Valid:
                return validTile;
            case PathHighlightState.Invalid:
                return invalidTile;
            default:
                return normalTile;
        }
    }

    private void SetCellHighlight(Vector3Int cell, TileBase tile)
    {
        if (highlightTilemap == null) return;
        if (!originalTiles.ContainsKey(cell))
        {
            originalTiles[cell] = highlightTilemap.GetTile(cell);
        }
        highlightTilemap.SetTile(cell, tile);
    }

    private void ClearLastHighlight()
    {
        if (lastHoveredCell != Vector3Int.zero && highlightTilemap != null)
        {
            if (originalTiles.ContainsKey(lastHoveredCell))
            {
                highlightTilemap.SetTile(lastHoveredCell, originalTiles[lastHoveredCell]);
            }
            else
            {
                highlightTilemap.SetTile(lastHoveredCell, null);
            }
        }
    }

    public void ClearAllHighlights()
    {
        if (highlightTilemap == null) return;
        foreach (var kvp in originalTiles)
        {
            highlightTilemap.SetTile(kvp.Key, kvp.Value);
        }
        originalTiles.Clear();
        lastHoveredCell = Vector3Int.zero;
        currentState = PathHighlightState.Normal;
    }

    public void StartDragging(bool canPlace = true)
    {
        isDragging = true;
        canPlaceItem = canPlace;
        currentState = canPlace ? PathHighlightState.Valid : PathHighlightState.Invalid;
    }

    public void StopDragging()
    {
        isDragging = false;
        canPlaceItem = false;
        currentState = PathHighlightState.Normal;
        ClearAllHighlights();
    }

    public void UpdateDragState(bool canPlace)
    {
        if (!isDragging) return;
        canPlaceItem = canPlace;
        currentState = canPlace ? PathHighlightState.Valid : PathHighlightState.Invalid;
    }

    public bool CanPlaceItemAt(Vector3 position)
    {
        Vector3Int cell = highlightTilemap.layoutGrid.WorldToCell(position);
        return currentPath.Contains(cell);
    }

    public Vector3Int GetCurrentHoveredCell()
    {
        return lastHoveredCell;
    }

    public Vector3 GetCurrentHoveredWorldPosition()
    {
        if (highlightTilemap == null) return Vector3.zero;
        return highlightTilemap.GetCellCenterWorld(lastHoveredCell);
    }

    public bool IsDragging => isDragging;
    public bool CanPlaceItem => canPlaceItem;

    private void OnStartFollowingPath(List<Vector3Int> path, Tilemap tilemap)
    {
        currentPath = new List<Vector3Int>(path);
        ClearAllHighlights();
    }

    private void OnFinishFollowingPath()
    {
        ClearAllHighlights();
    }

    public void SetPath(List<Vector3Int> path)
    {
        currentPath = new List<Vector3Int>(path);
        ClearAllHighlights();
    }

    public void AddPathPoint(Vector3Int point)
    {
        if (!currentPath.Contains(point))
        {
            currentPath.Add(point);
        }
    }

    public void RemovePathPoint(Vector3Int point)
    {
        currentPath.Remove(point);
    }

    public void ClearPath()
    {
        currentPath.Clear();
        ClearAllHighlights();
    }
} 